'use strict';
const db = uniCloud.database();
const userCollection = db.collection('users');

exports.main = async (event, context) => {
    console.log('user function called', event);
    const { action, data } = event;

    try {
        switch (action) {
            case 'register':
                return await register(data);
            case 'login':
                return await login(data);
            default:
                throw new Error('未知的操作类型');
        }
    } catch (error) {
        console.error('用户操作失败:', error);
        return {
            code: -1,
            message: error.message || '操作失败',
            data: null
        };
    }
};

// 注册
async function register(data) {
    const { phone, password } = data;

    // 验证手机号格式
    if (!/^1[3-9]\d{9}$/.test(phone)) {
        throw new Error('手机号格式不正确');
    }

    // 检查手机号是否已注册
    const existUser = await userCollection.where({
        phone: phone
    }).get();

    if (existUser.data && existUser.data.length > 0) {
        throw new Error('该手机号已注册');
    }

    // 创建新用户
    const userData = {
        phone,
        password, // 实际应用中需要对密码进行加密
        createTime: Date.now()
    };

    await userCollection.add(userData);

    return {
        code: 0,
        message: '注册成功'
    };
}

// 登录
async function login(data) {
    const { phone, password } = data;

    // 查询用户
    const user = await userCollection.where({
        phone: phone,
        password: password // 实际应用中需要对密码进行加密比对
    }).get();

    if (!user.data || user.data.length === 0) {
        throw new Error('手机号或密码错误');
    }

    // 生成登录态
    const userInfo = {
        userId: user.data[0]._id,
        phone: user.data[0].phone,
        createTime: user.data[0].createTime
    };

    return {
        code: 0,
        message: '登录成功',
        data: userInfo
    };
} 